<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/10/23
 * Time: 18:14
 */

namespace app\common\model;


use app\common\model\dynamic\DynamicFlowItem;
use app\common\model\dynamic\DynamicFlowItemTeacher;
use app\common\model\teacher\Teacher;
use think\Db;
use think\Exception;
use think\Model;

/**
 * Class Topic
 * @package app\common\model
 *
 * @property integer id
 * @property string title
 * @property integer teacher_id
 * @property string play_date
 * @property integer participants_count
 * @property integer num_liked
 *
 * @property integer status
 */
class Topic extends Model implements IMakeDynamicFlow
{
    protected $table = 'topic';
    protected $pk = 'id';

    /**
     * @param $teacherId
     * @param $rows
     * @param $page
     * @param null $keywords
     * @return \think\Paginator
     */
    public static function manageList($teacherId, $rows, $page, $keywords = null) {

        $today = date('Y-m-d');
        $query = Db::table('topic a');
        $query->where('a.teacher_id','=', $teacherId);
        $query->order('a.id','desc');
        $query->field("a.*, a.play_date='$today' is_current");
        if (null !== $keywords) {
            $query->whereLike('a.title',"%$keywords%");
        }
        $result = $query->paginate($rows,false,['page'=>$page]);

        return $result;
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public static function del($id) {
        $sql = 'delete from topic where id=:id returning *';
        $result = Db::query($sql, ['id' => $id]);
        return $result;
    }

    public static function apiList($teacherId, $rows, $page, $uid = 0, $returnTotal = false) {

        $query = Db::table('topic');
        $query->where('teacher_id','=', $teacherId);
        $query->order('id','desc');
        $likedSQL = $uid>0 ? ",exists(select * from user_topic_liked l where l.topic_id=topic.id and l.uid=$uid) have_liked" : '';
        $query->field('topic.*' . $likedSQL);

        if ($returnTotal) {
            $result = $query->paginate($rows,false,['page'=>$page]);
            $list = $result->items();
            self::formatList($list);
            return ['list'=>$list, 'total'=>$result->total()];
        } else {
            $list = $query->page($page,$rows)->select();
            self::formatList($list);
            return ['list' => $list];
        }

    }

    /**
     * 获取信息，包括已点赞
     *
     * @param $id
     * @param int $uid
     * @return mixed
     */
    public static function apiInfo($id, $uid = 0) {
        $sql = <<<SQL
SELECT t.*,
  exists(SELECT 1 FROM user_topic_liked utl WHERE utl.topic_id=t.id AND utl.uid=:uid) have_liked 
FROM topic t 
WHERE t.id=:id
SQL;
        $re = Db::query($sql, ['id'=>$id, 'uid'=>$uid]);
        if (count($re) == 0) return null;

        $info = $re[0];
        $today = date('Y-m-d');
        $info['is_close'] = $info['play_date'] !== $today;

        return $info;
    }

    private static function formatList(& $list) {
        $today = date('Y-m-d');
        $yesterday = date('Y-m-d', strtotime($today.' -1 day'));
        foreach ($list as & $item) {
            $item['is_close'] = ($today !== $item['play_date']);
            if ($yesterday === $item['play_date']) {
                $item['play_date'] = '昨天';
            }
        }
    }



    /**
     * 累计参与人数
     *
     * @param $id
     */
    public static function increaseUserCount($id) {
        $sql = <<<SQL
UPDATE topic SET participants_count=participants_count+1 WHERE id=:id
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * 点赞接口
     * @param $uid
     * @param $topicId
     * @param bool $gave
     * @return bool
     */
    public static function gaveLike($uid, $topicId, $gave = true) {
        if ($gave) {
            $sql = <<<SQL
INSERT INTO user_topic_liked (uid, topic_id) VALUES (:uid, :topic_id)
ON CONFLICT DO NOTHING 
SQL;
        } else {
            $sql = <<<SQL
DELETE FROM user_topic_liked WHERE uid=:uid AND topic_id=:topic_id
SQL;
        }

        try{
            Db::startTrans();

            $n = Db::execute($sql, ['uid' => $uid, 'topic_id' => $topicId]);
            if ($n > 0) {
                $inc = $gave ? 1 : -1;
                $sql = <<<SQL
UPDATE topic SET num_liked=num_liked+:inc WHERE id=:id
SQL;
                Db::execute($sql, ['inc' => $inc, 'id' => $topicId]);
            }

            Db::commit();
            return true;
        }catch (Exception $ex){
            Db::rollback();
            return false;
        }

    }

    /**
     * 获取点赞数
     *
     * @param $id
     * @return mixed
     */
    public static function getLikedNumber($id) {
        $sql = 'select num_liked from topic where id=:id';
        $re = Db::query($sql, ['id'=>$id]);
        return $re[0]['num_liked'];
    }

    /**
     * 检查用户是否已点赞
     *
     * @param $uid
     * @param $topicId
     * @return bool
     */
    public static function haveLike($uid, $topicId) {
        $re = Db::query('select exists(select 1 from user_topic_liked where uid=:uid AND topic_id=:id) e', ['uid'=>$uid,'id'=>$topicId]);
        return $re[0]['e'] ?? false;
    }

    /**
     * 获取老师的最新话题
     *
     * @param $teacher_id
     * @return \stdClass
     */
    public static function getLatest($teacher_id) {
        $sql = <<<SQL
SELECT * FROM topic WHERE teacher_id=:tid ORDER BY id DESC 
SQL;
        $re = Db::query($sql, ['tid' => $teacher_id]);

        return $re[0] ?? new \stdClass();
    }

    /**
     * 检查话题的所有者
     *
     * @param $id
     * @param $teacherId
     * @return mixed
     */
    public static function checkOwn($id, $teacherId) {
        $sql = <<<SQL
SELECT exists(
  SELECT 1 FROM topic WHERE id=:id AND teacher_id=:tid
) e
SQL;
        $re = Db::query($sql, ['id'=>$id, 'tid'=>$teacherId]);
        return $re[0]['e'];
    }

    /**
     * 产生老师动态
     *
     * @param bool $isNew
     * @param integer $source
     * @return DynamicFlow
     */
    public function makeDynamicData(bool $isNew, int $source = DynamicFlow::SOURCE_SYSTEM): DynamicFlow
    {
        $teacher = Teacher::get($this->teacher_id);

        $dynamic = new DynamicFlow();
        $dynamic->df_time = time();
        $dynamic->df_source = $source;
        $dynamic->df_isfee = false;
        $dynamic->df_isnew = $isNew;

        $item = new DynamicFlowItem();
        $item->item_id = (int) $this->id;
        $item->item_title = $this->title;
        $item->item_summary = '';

        $item->item_topic = $this;

        $item_teacher = new DynamicFlowItemTeacher();
        $item_teacher->teacher_id = (int) $teacher->id;
        $item_teacher->teacher_name = $teacher->realname;
        $item_teacher->teacher_avatar = $teacher->avatar ?? Teacher::DEFAULT_AVATAR;
        $item_teacher->teacher_degree = $teacher->getDegreeName();
        $item->item_teacher = $item_teacher;

        $dynamic->df_class = DynamicFlow::CLASS_TOPIC_LIVE;
        $dynamic->df_type = DynamicFlow::TYPE_TOPIC_LIVE;

        $dynamic->df_value = $item;

        $dynamic->save();

        return $dynamic;

    }
}